import type { ColumnProps } from "./store/column";
import type { ImageProps } from "./store/utils";
import type { UserDataProps } from "./store/user";
import columnImage from "./assets/column.jpg";
import avatarImage from "./assets/avatar.jpg";

export function generateFitUrl(
  data: ImageProps,
  width: number,
  height: number,
  format = ["m_pad"]
) {
  if (data && data.url) {
    const formatStr = format.reduce((prev, current) => {
      return current + "," + prev;
    }, "");
    data.fitUrl =
      data.url +
      `?x-oss-process=image/resize,${formatStr}h_${height},w_${width}`;
  }
}

export function addColumnAvatar(
  data: ColumnProps | UserDataProps,
  width: number,
  height: number
) {
  if (data.avatar) {
    generateFitUrl(data.avatar, width, height);
  } else {
    const parseCol = data as ColumnProps;
    data.avatar = {
      fitUrl: parseCol.title ? columnImage : avatarImage,
    };
  }
}

export const arrToObj = <T extends { _id?: string }>(arr: T[]) => {
  return arr.reduce((prev, current) => {
    if (current._id) {
      prev[current._id] = current;
    }

    return prev;
  }, {} as { [key: string]: T });
};

export const objToArr = <T>(obj: { [key: string]: T }) => {
  // return Object.keys(obj).map((key) => obj[key]); // 2次遍历
  return Object.values(obj);
};
